package org.example.paymentservice.service.impl;

import lombok.RequiredArgsConstructor;
import org.example.paymentservice.dto.OrderRequest;
import org.example.paymentservice.entity.Order;
import org.example.paymentservice.repository.OrderRepository;
import org.example.paymentservice.service.OrderProcessor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.persistence.EntityNotFoundException;

@Service
@RequiredArgsConstructor
public class OrderProcessorImpl implements OrderProcessor {
    private final OrderRepository orderRepository;

    @Override
    @Transactional
    public Order createOrder(OrderRequest orderRequest) {
        Order order = new Order();
        order.setUserId(orderRequest.getUserId());
        order.setCourseId(orderRequest.getCourseId());
        order.setCourseTitle(orderRequest.getCourseTitle());
        order.setAmount(orderRequest.getAmount());
        order.setStatus(Order.PaymentStatus.PENDING);
        order.setPaymentMethod(orderRequest.getPaymentMethod());
        
        return orderRepository.save(order);
    }

    @Override
    public Order validateOrder(Long orderId) {
        Order order = getOrder(orderId);
        if (order.getStatus() != Order.PaymentStatus.PENDING) {
            throw new IllegalStateException("Order is not in PENDING status");
        }
        return order;
    }

    @Override
    @Transactional
    public void updateOrderStatus(Long orderId, Order.PaymentStatus status) {
        Order order = getOrder(orderId);
        order.setStatus(status);
        orderRepository.save(order);
    }

    @Override
    public Order getOrder(Long orderId) {
        return orderRepository.findById(orderId)
                .orElseThrow(() -> new EntityNotFoundException("Order not found"));
    }
}